import { TreeProps } from '@/typing';
import { getNodeById, depthEach } from '@/utils/tree';

// 通过id获取父节点
export const getParentById = (
  fields = { id: 'id', parentId: 'parentId' },
  id: string,
  data: Array<any>,
) => {
  const dataMap = {};
  data.forEach(e => (dataMap[e[fields.id]] = e));
  const currentParent = dataMap[id] || null;
  return currentParent;
};

// 获取tree数据中最高选中的节点
export const getHeightCheckedNodes = data => {
  return data.filter(item => {
    const parent = getParentById({ id: 'code', parentId: 'parentCode' }, item.parentCode, data);
    return !parent?.attributes?.checked;
  });
};

export type DataProps = {
  code: string;
  id?: string;
  leaf: boolean;
  level: number;
  name: string;
  parentCode: string;
  attributes?: any;
  children?: DataProps[] | any;
  collapse?: boolean;
  checked?: boolean;
  indeterminate?: boolean;
};

// 添加属性
export function addExtraAttribute(treeData: Array<TreeProps>, type: string): void {
  depthEach(treeData, item => {
    item.attributes.checked = false;
    item.attributes.indeterminate = false;
    item.attributes.collapse = false;
    item.attributes.type = type;
  });
}
// 更新当前节点的所有子节点
export function refreshAllSonNodes(node: TreeProps | any, status: boolean): void {
  if (!node) return;
  node.attributes.checked = status;
  node.attributes.indeterminate = false;
  if (node.children && node.children.length) {
    node.children.forEach((el: TreeProps) => {
      el.attributes.checked = status;
      el.attributes.indeterminate = false;
      refreshAllSonNodes(el, status);
    });
  }
}
// 更新当前节点的所有父节点
export function refreshAllParentNodes(node: TreeProps | any, treeData: Array<TreeProps>) {
  if (node) {
    let nullCount = 0;
    let fullCount = 0;
    node.children.forEach((item: TreeProps) => {
      if (!item.attributes.checked && !item.attributes.indeterminate) {
        nullCount++;
      } else if (item.attributes.checked && !item.attributes.indeterminate) {
        fullCount++;
      }
    });

    if (fullCount === node.children.length) {
      node.attributes.checked = true;
      node.attributes.indeterminate = false;
    } else if (nullCount === node.children.length) {
      node.attributes.checked = false;
      node.attributes.indeterminate = false;
    } else {
      node.attributes.checked = false;
      node.attributes.indeterminate = true;
    }

    // 通过code获取父级节点
    const parentNode = getNodeById('code', node.parentCode, treeData);
    // 递归计算父级
    parentNode && refreshAllParentNodes(parentNode, treeData);
  }
}

export interface CardItemProps {
  name: string;
  checked?: boolean;
  indeterminate?: boolean;
  data: DataProps[];
  type: string;
}
